import React, {Component} from 'react'
import {
    View, 
    Text, 
    Image, 
    TouchableOpacity, 
    Modal, 
    StyleSheet, 
    PermissionsAndroid,
    Platform} from 'react-native'
import {AudioRecorder, AudioUtils} from 'react-native-audio'
import Spinner from 'react-native-spinkit'
import styles from '../../config/styles'
import Icon from 'react-native-vector-icons/Ionicons'
import RNFetchBlob from 'react-native-fetch-blob'
import {dirName} from '../../helpers/fsHelper'


class AudioSelector extends Component {
    static defaultProps = {
        style: {},
        onFinished: undefined
    }

    constructor (props) {
        super(props)
        this.state = {
            modalVisible: false,
            recording: false,
            hasPermission: undefined        
        }
    }


    //检查权限
    _checkPermission() {
        if (Platform.OS !== 'android') {
          return Promise.resolve(true);
        }
  
        const rationale = {
          'title': '录制音频权限',
          'message': '需要录制音频的权限'
        };
  
        return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, rationale)
            .then((result) => {
                return (result === true || result === PermissionsAndroid.RESULTS.GRANTED);
            });
    }

    //开始录音
    async _record() {
        if (this.state.recording) return
  
        if (!this.state.hasPermission) return
  
        this.setState({recording: true});
  
        try {
            const filePath = await AudioRecorder.startRecording();
        } catch (error) {
            console.error(error);
        }
    }

    //结束录音
    async _stop() {
        if (!this.state.recording) return
  
        this.setState({stoppedRecording: true, recording: false});
  
        try {
            let filePath = await AudioRecorder.stopRecording();
            if (Platform.OS === 'android') {
                filePath = 'file://' + filePath
                this._finishRecording(filePath)
            }

            this.closeModal()
            return filePath;
        } catch (error) {
            console.error(error);
        }
    }

    //安卓和ios最终到这边返回一个录制完成的路径
    _finishRecording = (filePath) => {
        if (this.props.onFinished != undefined) {
            this.props.onFinished(filePath)
        }        
    }

    //初始化录音
    start_recording = () => {
         //检查权限
        this._checkPermission().then((hasPermission) => {
            if (!hasPermission) return
            this.state.hasPermission = hasPermission
    
            //初始化音频路径
            let date = new Date()
            //const dirs = RNFetchBlob.fs.dirs
            //const FILE_PATH = `${dirName()}/${date.getTime()}.aac`
            const audioPath = AudioUtils.DocumentDirectoryPath + `/${date.getTime()}.aac`
            AudioRecorder.prepareRecordingAtPath(audioPath, {
                SampleRate: 22050,
                Channels: 1,
                AudioQuality: "Low",
                AudioEncoding: "aac",
                AudioEncodingBitRate: 32000
            });

            //ios和安卓不同，需要额外起一个监听来获取结束后的filePath
            AudioRecorder.onFinished = (data) => {
                // Android callback comes in the form of a promise instead.
                if (Platform.OS === 'ios') {
                  this._finishRecording(data.audioFileURL);
                }
            };
            
            this._record()
        })
       // this.setState({modalVisible: true})
    }

    openModal = () => {
        this.setState({modalVisible: true})
    }

    closeModal = () => {
        if (this.state.recording) AudioRecorder.stopRecording()
        
        this.setState({modalVisible: false, recording: false})
    }

    modalTemplate = () => {
        const {recording} = this.state
        return(
            <Modal
                animationType={'slide'}
                visible={this.state.modalVisible}
                transparent={true}
                onRequestClose={() => {}}                
            >
                <TouchableOpacity
                    style={{flex: 1}}
                    onPress={() => {this.closeModal()}}
                >
                    <View style={{flex: 1}}>
                        <View style={{flex: 1, backgroundColor: 'rgba(0,0,0,0.5)'}} />
                        <View style={{backgroundColor: 'white', height: 200, alignItems: 'center', justifyContent: 'center'}}>
                            {
                                recording ? (
                                    <TouchableOpacity onPress={() => {this._stop()}} style={[styles.icon_container, {backgroundColor: '#00FF00'}]}>
                                        <View style={[styles.icon_inner_container]}>
                                            <Spinner type={'Wave'} color={'white'} />
                                        </View>
                                    </TouchableOpacity>
                                ) : (
                                    <TouchableOpacity 
                                        onPress={this.start_recording}
                                        style={[styles.icon_container]}>
                                        <View style={{justifyContent: 'center', alignItems: 'center', padding: 15}}>
                                            <Icon  name={'ios-mic-outline'} size={40} color={'white'}  />
                                        </View>
                                    </TouchableOpacity>
                                )
                            }
                           
                            <View>
                                <Text>{
                                    recording ? '正在录音...' : '点击开始录音'
                                }</Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
            </Modal>
        )
    }

    render () {
        return (
            <TouchableOpacity style={{flex: 1}} onPress={this.openModal}>
                <View style={[{alignItems: 'center', justifyContent: 'center'}, this.props.style]}>
                    <View style={[styles.icon_small_container]}>
                        <View style={{justifyContent: 'center', alignItems: 'center', padding: 15}}>
                            <Icon name={'ios-mic-outline'} size={30} color={'white'} />
                        </View>
                    </View>
                    <View style={{paddingTop: 10}}>
                        <Text>录音</Text>
                    </View>
                    {this.modalTemplate()}
                </View>
            </TouchableOpacity>
        )
    }
}

export default AudioSelector